import * as FingerprintJS from "@fingerprintjs/fingerprintjs";

const FINGERPRINT_STORAGE_KEY = "user_fingerprint";

/**
 * @author BelovedLYC
 * @date 2025-05-31
 * @description 获取用户唯一指纹并存储到本地存储如果指纹已存在，则直接返回存储的指纹，不再重新生成
 * @returns Promise<string> 用户指纹
 */
export async function getUserFingerprint(): Promise<string> {
  // 检查本地存储是否已有指纹
  const storedFingerprint = localStorage.getItem(FINGERPRINT_STORAGE_KEY);

  // 如果已存在指纹，直接返回
  if (storedFingerprint) {
    return storedFingerprint;
  }

  try {
    // 加载FingerprintJS
    const fpPromise = FingerprintJS.load();
    // 获取agent并生成指纹
    const fp = await fpPromise;
    const result = await fp.get();

    // 获取唯一的指纹ID
    const fingerprint = result.visitorId;

    // 存储到本地存储
    localStorage.setItem(FINGERPRINT_STORAGE_KEY, fingerprint);

    return fingerprint;
  } catch (error) {
    // 生成一个随机字符串作为备用指纹
    const fallbackFingerprint = `fallback_${Date.now()}_${Math.random()
      .toString(36)
      .substring(2, 15)}`;
    localStorage.setItem(FINGERPRINT_STORAGE_KEY, fallbackFingerprint);

    return fallbackFingerprint;
  }
}

/**
 * 检查是否有存储的指纹
 * @returns boolean 是否有存储的指纹
 */
export function hasSavedFingerprint(): boolean {
  return !!localStorage.getItem(FINGERPRINT_STORAGE_KEY);
}

/**
 * 获取存储的指纹，不重新生成
 * @returns string | null 已存储的指纹，如果不存在则返回null
 */
export function getSavedFingerprint(): string | null {
  return localStorage.getItem(FINGERPRINT_STORAGE_KEY);
}

/**
 * 清除存储的指纹
 */
export function clearFingerprint(): void {
  localStorage.removeItem(FINGERPRINT_STORAGE_KEY);
}
